package ext.tianma.project2.APQP.service;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.support.RemoteAccessor;
import org.springframework.stereotype.Service;

import wt.fc.PagingQueryResult;
import wt.fc.PagingSessionHelper;
import wt.fc.ReferenceFactory;
import wt.inf.team.ContainerTeamManagedState;
import wt.org.WTUser;
import wt.projmgmt.admin.Project2;
import wt.query.ArrayExpression;
import wt.query.ClassAttribute;
import wt.query.OrderBy;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.workflow.definer.WfProcessTemplate;
import wt.workflow.definer.WfProcessTemplateMaster;
import wt.workflow.engine.WfProcess;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;

import com.ptc.projectmanagement.plan.PlanActivity;
import com.ptc.projectmanagement.plan.PlannableState;

import ext.tianma.project2.APQP.constants.APQPProjectConstant;
import ext.tianma.project2.util.ProjectUtil;
import ext.tianma.util.TMUtil;

@Service
public class HomeService extends RemoteAccessor{
	
	@Autowired
	APQPPlanActivityService planactivityservice;
	
	/**
	 * 待我处理的任务
	 * @param user
	 * @param state
	 * @param isStandard
	 * @param page
	 * @param rows
	 * @throws WTException
	 * @author xucr
	 * @throws JSONException 
	 * @CreateDate 2020年8月18日
	 */
	public JSONObject getMyToDoTask(WTUser user, int page, int rows) throws WTException, JSONException {
		/**
		 * 待处理：项目进行中，且状态为进行中、不达标、“我”的活动
		 * */
		String[] projectStates = {ContainerTeamManagedState.RUNNING.toString()};
		String[] planstates = {PlannableState.INPROCESS.toString()};
		QuerySpec qs = queryMyPlanActivity(projectStates, user, planstates, APQPProjectConstant.NO);
		
		JSONObject rsult = reading(qs, page, rows);
		return rsult;
	}
	
	/**
	 * 我已完成的任务
	 * @param user
	 * @param state
	 * @param page
	 * @param rows
	 * @throws WTException
	 * @author xucr
	 * @throws JSONException 
	 * @CreateDate 2020年8月20日
	 */
	public JSONObject getMyCompletedTasks(WTUser user, int page, int rows) throws WTException, JSONException {
		/**
		 * 已完成：
		 * 	①所有状态项目，且状态为已完成、“我”的活动
		 * 	②所有状态项目，且状态为进行中、已达标、“我”的活动
		 * 等价于：所有状态、已达标、我的活动
		 * */
//		String[] planStates1 = {PlannableState.INPROCESS.toString()};
//		QuerySpec qs1 = queryMyPlanActivity(null, user, planStates1, "");
//		
//		String[] planStates2 = {PlannableState.INPROCESS.toString()};
//		QuerySpec qs2 = queryMyPlanActivity(null, user, planStates2, APQPProjectConstant.YES);
		
		QuerySpec qs = queryMyPlanActivity(null, user, null, APQPProjectConstant.YES);
	    JSONObject rsult = reading(qs, page, rows);
	    return rsult;
	}
	
	/**
	 * 封装活动待办表格
	 * @param qs
	 * @param page
	 * @param rows
	 * @return
	 * @throws WTException
	 * @throws JSONException
	 * @author xucr
	 * @CreateDate 2020年9月10日
	 */
	private JSONObject reading(QuerySpec qs, int page, int rows) throws WTException, JSONException {
		//分页查询
	    PagingQueryResult qr = PagingSessionHelper.openPagingSession((page - 1) * rows, rows, qs);
	    
	    JSONObject jsonObj = null;
	    JSONArray array = new JSONArray();
	    String [] stdAttrs = {"isUpload","isStandard"};
	    while(qr.hasMoreElements()){
	    	jsonObj = new JSONObject();
	    	Object [] obj = (Object[]) qr.nextElement();
	    	PlanActivity plan = (PlanActivity) obj[0];
	    	Project2 project = (Project2) plan.getContainer();
	    	String projectName = project.getName();
	    	String planName = plan.getName();
	    	WTUser u = (WTUser) project.getCreator();
	    	String creator = u.getName() + "/" + u.getFullName();
	    	String startDate = TMUtil.timestampToString(plan.getStartDate(), "yyyy-MM-dd") ;
	    	
	    	jsonObj.put("projectName", projectName);
	    	jsonObj.put("planName", planName);
	    	jsonObj.put("creator", creator);
	    	jsonObj.put("startDate", startDate);
	    	jsonObj.put("projectOid", TMUtil.obj2Oid(project));
	    	jsonObj.put("planActivityOid", TMUtil.obj2Oid(plan));
	    	
	    	//判断活动是否显示【启用/不启用】
	    	planactivityservice.getPlanactivitySTDAttr(plan, stdAttrs, jsonObj);
	    	String isUpload = jsonObj.getString("isUpload");
	    	String isStandard = jsonObj.getString("isStandard");
	    	if((APQPProjectConstant.YES.equals(isUpload) && APQPProjectConstant.NO.equals(isStandard))
	    			|| APQPProjectConstant.YES_VALUE.equals(isUpload) && APQPProjectConstant.NO_VALUE.equals(isStandard)) {
	    		jsonObj.put("showComplete", true);
	    	} else {
	    		jsonObj.put("showComplete", false);
	    	}
	    	array.put(jsonObj);
	    }
	    
	    JSONObject rsult = ProjectUtil.respInfo(array, qr.getTotalSize());
	    return rsult;
	}
	
	/**
	 * "我"的APQP流程任务
	 * @param user
	 * @param states
	 * @throws WTException
	 * @author xucr
	 * @throws JSONException 
	 * @CreateDate 2020年8月20日
	 */
	public JSONObject getMyWorkItems(WTUser user, String [] states,  int page, int rows) throws WTException, JSONException {
		
		QuerySpec qs = getPagingOwnedWorkItems(user, states, APQPProjectConstant.APQP_WFPROCESSTEMPLATE_NAME);
		
		PagingQueryResult qr = PagingSessionHelper.openPagingSession((page - 1) * rows, rows, qs);
		
		JSONObject jsonObj = null;
	    JSONArray array = new JSONArray();
	    ReferenceFactory rf = new ReferenceFactory();
	    while(qr.hasMoreElements()){
	    	jsonObj = new JSONObject();
	    	Object [] obj = (Object[]) qr.nextElement();
	    	WfProcess process = (WfProcess) obj[0];
	    	WorkItem workitem = (WorkItem) obj[1];
	    	String activityName = (String) obj[2];
	    	Project2 proejct = (Project2) TMUtil.oid2Obj(process.getBusinessObjReference());
//	    	String processName = process.getName();
	    	String creator = process.getCreator().getName() + "/" + process.getCreator().getFullName();
	    	String startDate = TMUtil.timestampToString(process.getCreateTimestamp(), "yyyy-MM-dd hh:mm:ss") ;
	    	
	    	jsonObj.put("projectName", proejct.getName());
	    	jsonObj.put("processName", activityName);
	    	jsonObj.put("creator", creator);
	    	jsonObj.put("startDate", startDate);
	    	jsonObj.put("wfProcessOid", rf.getReferenceString(process));
	    	jsonObj.put("workItemOid", TMUtil.obj2Oid(workitem));
	    	
	    	array.put(jsonObj);
	    }
	    
	    JSONObject rsult = ProjectUtil.respInfo(array, qr.getTotalSize());
	    return rsult;
	}
	
	
	
	/**
	 * 查询活动
	 * @param projectStates 项目状态
	 * @param user 用户
	 * @param state 活动状态
	 * @param isStandard 是否达标
	 * @return
	 * @throws WTException
	 * @author xucr
	 * @CreateDate 2020年8月18日
	 */
	private QuerySpec queryMyPlanActivity(String [] projectStates, WTUser user, String [] planStates, String standard) throws WTException {
		QuerySpec qs = new QuerySpec();
	    int pa = qs.appendClassList(PlanActivity.class, true);
	    int p2 = qs.appendClassList(Project2.class, false);
	    qs.setAdvancedQueryEnabled(true);
	    
	    SearchCondition sc = new SearchCondition(PlanActivity.class, "containerReference.key.id" , 
	    		Project2.class, "thePersistInfo.theObjectIdentifier.id");
	    qs.appendWhere(sc, new int[] {pa, p2});
	    
	    //是否达标
	    if(StringUtils.isNotEmpty(standard)) {
	    	String isStandardQueryName = ProjectUtil.getQueryName("isStandard", APQPProjectConstant.APQP_PLANACTIVITY);
		    SearchCondition sc1 = new SearchCondition(PlanActivity.class, isStandardQueryName , SearchCondition.EQUAL, standard);
		    qs.appendAnd();
		    qs.appendWhere(sc1, new int[] {pa});
	    }
	    
	    //状态
	    if(null != planStates && planStates.length > 0) {
	    	SearchCondition sc2 = new SearchCondition(new ClassAttribute(PlanActivity.class,PlanActivity.PLANNABLE_STATE),
	    			SearchCondition.IN, new ArrayExpression(planStates));
	    	qs.appendAnd();
		    qs.appendWhere(sc2, new int[] {pa});
	    }
	    
	    //用户
	    if(null != user) {
	    	Long userId = user.getPersistInfo().getObjectIdentifier().getId();
		    SearchCondition sc3 = new SearchCondition(PlanActivity.class, "ownership.owner.key.id" , SearchCondition.EQUAL, userId);
		    qs.appendAnd();
		    qs.appendWhere(sc3, new int[] {pa});
	    }
	    
	    //项目状态
	    if(null != projectStates && projectStates.length > 0) {
	    	SearchCondition sc4 = new SearchCondition(new ClassAttribute(Project2.class,"containerTeamManagedInfo.state"),
	    			SearchCondition.IN, new ArrayExpression(projectStates));
	    	qs.appendAnd();
			qs.appendWhere(sc4, new int[] {p2});
	    }
	    qs.appendOrderBy(new OrderBy(new ClassAttribute(PlanActivity.class,PlanActivity.MODIFY_TIMESTAMP),true),new int[]{0});//更新时间排序
	    logger.info("queryMyPlanActivity >> sql >> " + qs.toString());
	    return qs;
	}
	
	 /**
	 * 查询流程
	 * @param onwer
	 * @param states
	 * @param processTempName
	 * @return
	 * @throws WTException
	 * @author xucr
	 * @CreateDate 2020年8月20日
	 */
	private QuerySpec getPagingOwnedWorkItems(WTUser onwer, String[] states, String processTempName) throws WTException {
		QuerySpec qs = new QuerySpec();
		int wf = qs.appendClassList(WfProcess.class, true);
		int wa = qs.appendClassList(WfAssignedActivity.class, false);
		int wk = qs.appendClassList(WorkItem.class, true);
	    qs.setAdvancedQueryEnabled(true);
	    
//	    select wa.name, wf.name, wf.ida3a5, wk.*
//	    from pdm.wfprocess wf, pdm.wfassignedactivity wa, pdm.workitem wk
//	   where wa.ida3parentprocessref = wf.ida2a2
//	     and wk.ida3a4 = wa.ida2a2
//	     and wk.ida3a2ownership = '11'
//	     and wk.status in ('POTENTIAL')	--workitem状态 待处理
//	     and wf.ida3a5 = '102311';		-- 流程模板：具体到流程类型
	    
	    //wa.ida3parentprocessref = wf.ida2a2
	    SearchCondition sc1 = new SearchCondition(WfAssignedActivity.class, "parentProcessRef.key.id",
	    		WfProcess.class, "thePersistInfo.theObjectIdentifier.id");
	    qs.appendWhere(sc1, new int [] {wa, wf});
	    
	    //wk.ida3a4 = wa.ida2a2
	    SearchCondition sc2 = new SearchCondition(WorkItem.class, "source.key.id",
	    		WfAssignedActivity.class, "thePersistInfo.theObjectIdentifier.id");
	    qs.appendAnd();
	    qs.appendWhere(sc2, new int [] {wk, wa});
	    
	    //wk.ida3a2ownership = '11'
	    if(null != onwer) {
	    	Long userId = onwer.getPersistInfo().getObjectIdentifier().getId();
	 	    SearchCondition sc3 = new SearchCondition(WorkItem.class, "ownership.owner.key.id", SearchCondition.EQUAL, userId);
	 	    qs.appendAnd();
	 	    qs.appendWhere(sc3, new int [] {wk});
	    }
	    
	    //wk.status in ('POTENTIAL') --orkitem状态 待处理
	    if(null != states && states.length > 0) {
	    	SearchCondition sc4 = new SearchCondition(new ClassAttribute(WorkItem.class,"status"),SearchCondition.IN, new ArrayExpression(states));
		    qs.appendAnd();
		    qs.appendWhere(sc4, new int [] {wk});
	    }
	    
	    //wf.ida3a5 = '102311'  -- 流程模板：具体到流程类型
	    if(StringUtils.isNotEmpty(processTempName)) {
	    	int wtm = qs.appendClassList(WfProcessTemplateMaster.class, false);
	    	int wt = qs.appendClassList(WfProcessTemplate.class, false);
//	    	WfProcessTemplate wftemp = SubmitBomReview.getWfProcessTemplateByName(processTempName);
//		    Long wftempId = wftemp.getPersistInfo().getObjectIdentifier().getId();
//		    SearchCondition sc5 = new SearchCondition(WfProcess.class, "template.key.id", SearchCondition.EQUAL, wftempId);
//		    qs.appendAnd();
//		    qs.appendWhere(sc5, new int [] {wf});
		    
//		    and wtm.name = '资料外发审批流程'
	    	SearchCondition sc5 = new SearchCondition(WfProcessTemplateMaster.class, WfProcessTemplateMaster.NAME, 
	    			SearchCondition.EQUAL, processTempName);
	    	qs.appendAnd();
			qs.appendWhere(sc5, new int [] {wtm});
	    	
//    	    and wt.ida3masterreference = wtm.ida2a2
	    	SearchCondition sc6 = new SearchCondition(WfProcessTemplate.class, "masterReference.key.id", 
	    			WfProcessTemplateMaster.class, "thePersistInfo.theObjectIdentifier.id");
	    	qs.appendAnd();
			qs.appendWhere(sc6, new int [] {wt,wtm});
	    	
//    	    and wf.ida3a5 = wt.ida2a2;
	    	SearchCondition sc7 = new SearchCondition(WfProcess.class, "template.key.id", 
	    			WfProcessTemplate.class, "thePersistInfo.theObjectIdentifier.id");
	    	qs.appendAnd();
			qs.appendWhere(sc7, new int [] {wf, wt});
	    }
	    qs.appendOrderBy(new OrderBy(new ClassAttribute(WorkItem.class,WorkItem.MODIFY_TIMESTAMP),true),new int[]{wk});
	    qs.appendSelectAttribute("name", wa, false);
	    logger.info("sql>>>:" + qs.toString());
	    return qs;
	}
}
